package org.developer.websocketserver.client;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ThreadsDemoClient {

    public static void main(String[] args) throws IOException {

        int corePoolSize = 2;
        int maximumPoolSize = 4;
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        ThreadFactory threadFactory = new NameThreadFactory();
        RejectedExecutionHandler handler = new CustomIgnorePolicy();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        executor.prestartAllCoreThreads();//预启动所有核心线程

        for (int i = 0; i < 10; i++) {

            CustomTask task = new CustomTask(String.valueOf(i));
            executor.execute(task);
        }

        System.in.read();
    }

    /**
     * 线程工厂
     */
    static class NameThreadFactory implements ThreadFactory {

        private final AtomicInteger mThreadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement());
            log.info("\t[" + t.getName() + "]" + "has been created");
            return t;
        }
    }

    /**
     * 自定义拒绝策略类
     */
    public static class CustomIgnorePolicy implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

            log.error(r.toString() + "rejected");
        }
    }

    /**
     * 自定义任务类
     */
    static class CustomTask implements Runnable {

        private String name;

        public CustomTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {

                log.info(this.toString() + "is running");
                Thread.sleep(3000);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
